package com.example.administrator.energyida.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.energyida.MainActivity;
import com.example.administrator.energyida.R;
import com.example.administrator.energyida.activity.FormCompanyInfoActivity;
import com.example.administrator.energyida.activity.FormFactoryInfoActivity;
import com.example.administrator.energyida.beans.CompanyBean;
import com.example.administrator.energyida.util.LoadingDialog;
import com.example.administrator.energyida.util.OceanUtil;
import com.example.administrator.energyida.util.Validator;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends Activity implements View.OnClickListener {

    private RelativeLayout relativeLayout_register;
    private ImageView img_login_logo;
    private EditText edit_login_email;
    private EditText edit_login_password;
    private CheckBox check_login_remember;
    private CheckBox check_login_auto;
    private Button btn_login_signIn;
    private TextView text_login_forget;
    private TextView text_login_signUp;

    private String response;
    private String responseFirst;

    private Handler handler;
    private List<CompanyBean.ContentBean> listCompanyBeans = new ArrayList<>();

    private QMUITipDialog qmuiTipDialog;

    private String email;
    private String password;
    private Boolean firstLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
        initHandler();
        setListeners();

        SharedPreferences sharedPreferences1 = getSharedPreferences("auto", MODE_PRIVATE);
        boolean auto = sharedPreferences1.getBoolean("auto", false);
        String auto_name = sharedPreferences1.getString("name", "");
        String auto_pass = sharedPreferences1.getString("pass", "");
        if (auto) {
            edit_login_email.setText(auto_name);
            edit_login_password.setText(auto_pass);
            check_login_auto.setChecked(true);
            submit();
        } else {
            SharedPreferences sharedPreferences2 = getSharedPreferences("remember", MODE_PRIVATE);
            boolean rem = sharedPreferences2.getBoolean("rem", false);
            String rem_name = sharedPreferences2.getString("name", "");
            String rem_pass = sharedPreferences2.getString("pass", "");
            if (rem) {
                edit_login_email.setText(rem_name);
                edit_login_password.setText(rem_pass);
                check_login_remember.setChecked(true);
            } else {
                String email = getIntent().getStringExtra("email");
                String password = getIntent().getStringExtra("password");

                edit_login_email.setText(email);
                edit_login_password.setText(password);
            }
        }

    }

    /**
     * 初始化Handler
     */
    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        if (response.contains("10001")) {
                            Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                            // 存放登录成功的用户数据
                            SharedPreferences spAccount = getSharedPreferences("account", MODE_PRIVATE);
                            SharedPreferences.Editor editor = spAccount.edit();
                            editor.putString("email", email);
                            editor.putString("password", password);
                            editor.commit();
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            if (firstLogin) {
                                Intent intent = new Intent(LoginActivity.this, FormCompanyInfoActivity.class);
                                intent.putExtra("from", "Login");
                                startActivity(intent);
                                finish();
                            }else {
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                        if (response.contains("-10003")) {
                            Toast.makeText(LoginActivity.this, "用户不存在", Toast.LENGTH_SHORT).show();
                        }
                        if (response.contains("-10002")) {
                            Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 2:
                        if (responseFirst.contains("10007")) {
                            Gson gson = new Gson();
                            CompanyBean companyBean = gson.fromJson(responseFirst, CompanyBean.class);
                            listCompanyBeans = companyBean.getContent();
                            String s1 = listCompanyBeans.get(0).getCity();
                            if (s1 == null) {
                                firstLogin = true;
                            } else {
                                firstLogin = false;
                            }
                        }
                        if (responseFirst.contains("-20007")) {
                            firstLogin = true;
                        }
                        break;
                    default:
                        break;
                }
                qmuiTipDialog.dismiss();
            }
        };
    }

    /**
     * 对记住密码和自动登录的复选框的监听事件
     */
    private void setListeners() {
        check_login_remember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String name = edit_login_email.getText().toString().trim();
                String password = edit_login_password.getText().toString().trim();
                SharedPreferences sharedPreferences = getSharedPreferences("remember", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                if (isChecked) {
                    editor.putBoolean("rem", true);
                    editor.putString("name", name);
                    editor.putString("pass", password);
                } else {
                    check_login_auto.setChecked(false);
                    editor.putBoolean("rem", false);
                }
                editor.commit();
            }
        });

        check_login_auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String name = edit_login_email.getText().toString().trim();
                String password = edit_login_password.getText().toString().trim();
                SharedPreferences sharedPreferences = getSharedPreferences("auto", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                if (isChecked) {
                    editor.putBoolean("auto", true);
                    editor.putString("name", name);
                    editor.putString("pass", password);
                    check_login_remember.setChecked(true);
                } else {
                    editor.putBoolean("auto", false);
                }
                editor.commit();
            }
        });

    }

    /**
     * 初始化控件
     */
    private void initView() {
        relativeLayout_register = findViewById(R.id.relativeLayout_register);
        img_login_logo = findViewById(R.id.img_login_logo);
        edit_login_email = findViewById(R.id.edit_login_email);
        edit_login_password = findViewById(R.id.edit_login_password);
        check_login_remember = findViewById(R.id.check_login_remember);
        check_login_auto = findViewById(R.id.check_login_auto);
        btn_login_signIn = findViewById(R.id.btn_login_signIn);
        text_login_forget = findViewById(R.id.text_login_forget);
        text_login_signUp = findViewById(R.id.text_login_signUp);

        btn_login_signIn.setOnClickListener(this);
        text_login_forget.setOnClickListener(this);
        text_login_signUp.setOnClickListener(this);

        // 设置状态栏的颜色
        StatusBarUtil.setTranslucentForImageView(this, 50, relativeLayout_register);
    }

    /**
     * 点击事件
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login_signIn:
                submit();
                break;
            case R.id.text_login_forget:

                break;
            case R.id.text_login_signUp:
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 验证并提交
     */
    private void submit() {
        // validate
        email = edit_login_email.getText().toString().trim();
        if (TextUtils.isEmpty(email)) {
            Toast.makeText(this, "请输入邮箱", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!Validator.isEmail(email)) {
            Toast.makeText(this, "请输入正确的邮箱格式", Toast.LENGTH_SHORT).show();
            return;
        }

        password = edit_login_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!Validator.isPassword(password)) {
            Toast.makeText(this, "请输入正确的密码格式", Toast.LENGTH_SHORT).show();
            return;
        }

        //判断第一次登陆
        JSONObject getCompanyPoint = new JSONObject();
        try {
            getCompanyPoint.put("email", email);
            getCompanyPoint.put("mode", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new OceanUtil("getAccountAllInfo.php", getCompanyPoint, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                responseFirst = strResponse;
                Message message = new Message();
                message.what = 2;
                handler.sendMessage(message);
            }
        }).postInfo();

        // TODO validate success, do something

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("email", email);
            jsonObject.put("password", password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        qmuiTipDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在登录")
                .create();
        qmuiTipDialog.show();

        new OceanUtil("login.php", jsonObject, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                response = strResponse;
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }).postInfo();


    }
}
